import { Button, message, Tag, Popconfirm } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import DetailsForm from './components/DetailsForm';
import { operateInterface, queryAppJobList, updateInterface } from './service';

const TableList = () => {
  const actionRef = useRef();
  const [detailModalVisible, handleDetailModalVisible] = useState(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [detailType, setDetailType] = useState('');

  /**
   *  操作接口
   * @param selectedRows
   */

  const handleOper = async (params, operType) => {
    if (params.status === '0' && operType === 'del') {
      message.warn('请先停掉定时任务再删除');
      return;
    }
    message.loading('正在操作', 0);
    await operateInterface({
      id: params.id,
      type: operType,
      appjobname: params.appjobname,
      jobkey: params.jobkey,
    })
      .then((res) => {
        if (res.code === 200) {
          message.destroy();
          message.success('操作成功！');
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.destroy();
          message.error('操作失败请重试！');
        }
      })
      .catch(() => {
        message.destroy();
        message.error('操作失败');
      });
  };

  const handleEdit = (params) => {
    /* 运行状态不允许编辑 */
    if (params.status === '0') {
      message.warning('请先暂停任务再进行编辑');
      return;
    }
    handleDetailModalVisible(true);
    setStepFormValues(params);
    setDetailType('edit');
  };
  /**
   *  更新或新增接口
   * @param selectedRows
   */

  const handleUpdate = async (row) => {
    message.loading('正在操作', 0);
    await updateInterface(row)
      .then((res) => {
        if (res.code === 200) {
          message.destroy();
          message.success('操作成功，即将刷新');
          handleDetailModalVisible(false);
          setStepFormValues({});
          setDetailType('');
          if (actionRef.current) {
            actionRef.current.reload();
          }
          return;
        }
        if (res.code === 400) {
          message.destroy();
          message.error('数据库中已存在该监控名称和任务Key组合，请保持他们的唯一性');
          return;
        }
        message.destroy();
        message.error('操作失败，请检查参数再重试');
      })
      .catch(() => {
        message.destroy();
        message.error('操作失败，请检查参数再重试');
      });
  };

  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      sorter: false,
      hideInTable: true,
      search: false,
    },
    {
      title: '监控名称',
      key: 'appjobname',
      dataIndex: 'appjobname',
      sorter: true,
    },
    {
      title: '接口描述',
      key: 'descr',
      dataIndex: 'descr',
      sorter: false,
    },
    {
      title: '请求方式',
      key: 'requestMethod',
      dataIndex: 'requestMethod',
      sorter: true,
      search: false,
    },
    {
      title: '监控频率',
      key: 'jobcron',
      dataIndex: 'jobcron',
      sorter: false,
      search: false,
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      sorter: true,
      hideInSearch: true,
      render: (text, index) => {
        const color = text === '0' ? '#ff4d4f' : '#FFB800';
        const context = text === '0' ? '执行中' : '暂停中';
        return (
          <Tag color={color} key={index}>
            {context}
          </Tag>
        );
      },
    },
    {
      title: '更新时间',
      key: 'updatetime',
      dataIndex: 'updatetime',
      sorter: true,
      search: false,
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      valueType: 'option',
      width: 300,
      render: (text, record) => {
        return (
          <>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                handleEdit(record);
              }}
            >
              编辑
            </Button>
            &nbsp;
            <Button
              type="primary"
              size="small"
              style={{ background: '#009688', borderColor: '#009688' }}
              onClick={() => {
                handleOper(record, 'run');
              }}
            >
              执行
            </Button>
            &nbsp;
            <Button
              type="primary"
              size="small"
              danger
              style={{ display: record.status === '0' ? '' : 'none' }}
              onClick={() => {
                handleOper(record, 'paused');
              }}
            >
              暂停
            </Button>
            <Button
              type="primary"
              size="small"
              style={{
                background: '#FFB800',
                borderColor: '#FFB800',
                display: record.status === '1' ? '' : 'none',
              }}
              onClick={() => {
                handleOper(record, 'resume');
              }}
            >
              恢复
            </Button>
            &nbsp;
            <Popconfirm title="确认删除吗?" onConfirm={() => handleOper(record, 'del')}>
              <Button
                type="primary"
                size="small"
                danger
                onClick={() => {
                  setStepFormValues(record);
                }}
              >
                删除
              </Button>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleDetailModalVisible(true);
              setStepFormValues({});
              setDetailType('add');
            }}
          >
            新增
          </Button>,
        ]}
        request={(params, sorter, filter, type = '0') =>
          queryAppJobList({ ...params, sorter, filter, type })
        }
        columns={columns}
        search={{
          collapsed: false,
          collapseRender: () => false,
        }}
      />

      {detailType && detailModalVisible ? (
        <DetailsForm
          key="detailModal"
          onSubmit={async (value) => {
            await handleUpdate(value);
          }}
          onCancel={() => {
            handleDetailModalVisible(false);
            setStepFormValues({});
            setDetailType('');
          }}
          detailModalVisible={detailModalVisible}
          values={stepFormValues}
          detailType={detailType}
        />
      ) : null}
    </PageContainer>
  );
};

export default TableList;
